/**
 * 
 */
package Client.View;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import utils.ImagePanel;
import Client.Model.GameModel;

/**
 * @author Rodrigo
 * 
 */

@SuppressWarnings("serial")
public class InitialView extends JPanel implements Observer{
	
	private GameModel model;
	
	private JButton loginBtn, registerBtn;
	private JTextField serverAddr, serverPort, username;
	private JPasswordField password, passwordConfirmation;
	private JPanel serverInfoPanel, accountPanel, topPanel, btnPanel;
	private JCheckBox checkbox;
	private JLabel confirmPassLbl;
	
	private int height;
	private int width;
	
	public InitialView(GameModel m, int height, int width){
		this.model = m;
		
		model.addObserver(this);
		
		this.height = height;
		this.width = width;
		
		this.setPreferredSize(new Dimension(this.width, this.height));		
		
		setView();
		setListeners();
		
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		
		revalidate();
		repaint();
		
	}
	
	private void setView(){
		
		this.setBackground(LoginFrame.DEFAULT_BG_COLOR);
		
		
		loginBtn = new JButton("Login");
		registerBtn = new JButton("Register");
		serverAddr = new JTextField(20);
		serverAddr.setText("localhost");
		serverPort = new JTextField();
		serverPort.setText("1234");
		username = new JTextField();;
		password = new JPasswordField();
		passwordConfirmation = new JPasswordField();
		confirmPassLbl = new JLabel("Confirm Password:");
		btnPanel = new JPanel();
		
		checkbox = new JCheckBox("New Account");		
		checkbox.setOpaque(false);
		
		topPanel = new JPanel();
		topPanel.setPreferredSize(new Dimension(width, 100));
		topPanel.setBackground(LoginFrame.DEFAULT_BG_COLOR);
		topPanel.add(new ImagePanel("C:\\Users\\Rodrigo\\Dropbox\\Trabalhos\\PDist\\Partilha PDist\\logo.png", 0));
		
		serverInfoPanel = new JPanel();
		serverInfoPanel.setLayout(new GridLayout(2,2));
		serverInfoPanel.setBackground(LoginFrame.DEFAULT_BG_COLOR);
		serverInfoPanel.setPreferredSize(new Dimension(width-70, 60));
		
			serverInfoPanel.add(new JLabel("Server Address:"));
			serverInfoPanel.add(serverAddr);
			
			serverInfoPanel.add(new JLabel("Port:"));
			serverInfoPanel.add(serverPort);
		
			
		accountPanel = new JPanel(new GridLayout(4, 2));
		accountPanel.setBackground(LoginFrame.DEFAULT_BG_COLOR);	
		accountPanel.setPreferredSize(new Dimension(width-50, 180));
		accountPanel.setBorder(new EmptyBorder(50, 0, 0, 0));
		
			accountPanel.add(new JLabel("Username:"));
			accountPanel.add(username);
			
			accountPanel.add(new JLabel("Password:"));
			accountPanel.add(password);
			
			
			accountPanel.add(confirmPassLbl);
			accountPanel.add(passwordConfirmation);
			
			confirmPassLbl.setVisible(false);
			passwordConfirmation.setVisible(false);
			
			accountPanel.add(checkbox);
			accountPanel.add(btnPanel);
			
			btnPanel.setBackground(LoginFrame.DEFAULT_BG_COLOR);
			
			btnPanel.add(registerBtn);
			btnPanel.add(loginBtn);
			
			registerBtn.setVisible(false);
			
		//this.setLayout(null);
		this.add(topPanel);		
		this.add(serverInfoPanel);
		this.add(accountPanel);
				
	}
	
	private void setListeners(){ 
		
		checkbox.addItemListener(new ItemListener() {

		    public void itemStateChanged(ItemEvent e) {
		       
		    	if (checkbox.isSelected()){
		    		registerBtn.setVisible(true);
		    		loginBtn.setVisible(false);
		    		confirmPassLbl.setVisible(true);
		    		passwordConfirmation.setVisible(true);
		    	}
		    	else{
		    		registerBtn.setVisible(false);
		    		loginBtn.setVisible(true);
		    		confirmPassLbl.setVisible(false);
		    		passwordConfirmation.setVisible(false);
		    	}
		    		
		    	
		    	
		    }
		});
		
		registerBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				
				int res, port;
				InetAddress addr = null;
				
				char [] p1, p2;
				
				p1 = password.getPassword();
				p2 = passwordConfirmation.getPassword();
								
				if (!passwordMatches(p1, p2)){
					
					JOptionPane.showMessageDialog(InitialView.this, "Passwords não correspondem!");
					return;
				}
				else
					if (p1.length<3){
						JOptionPane.showMessageDialog(InitialView.this, "Tamanho minimo: 3 caracteres!");
						return;
					}
									
				try {
					addr = InetAddress.getByName(serverAddr.getText());
					port = Integer.parseInt(serverPort.getText());

					switch (res = model.doRegister(username.getText(), new String(password.getPassword()), addr, port)){	
					
						case GameModel.REGISTER_ERROR:
							JOptionPane.showMessageDialog(null,"Erro ao Registar!");
							System.out.println("Erro ao Registar!");
							break;
							
						case GameModel.REGISTER_OK:
							//JOptionPane.showMessageDialog(null,"Registado com sucesso!");
							System.out.println("Registado com sucesso!");
							break;

						case GameModel.CONNECTION_ERROR:
							JOptionPane.showMessageDialog(null,"Erro na ligação!");
							System.out.println("Erro na ligação!");
							break;
					
						default: System.out.println("Resultado: " + res);
					}
					
				} catch (UnknownHostException e1) {
					e1.printStackTrace();
				}catch(Exception ex){
					ex.printStackTrace();				
				}
				
				
			
			}

			private boolean passwordMatches(char[] p1, char[] p2) {
				
				if (p1.length != p2.length)
					return false;
				
				for (int i=0; i<p1.length; i++){
					if (p1[i] != p2[i])
						return false;
				}
				
				return true;
				
			}
		});
		
		loginBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				
				super.mousePressed(e);
				
				int res, port;
				InetAddress addr = null;
				
				try {
					addr = InetAddress.getByName(serverAddr.getText());
					port = Integer.parseInt(serverPort.getText());

					switch (res = model.doLogin(username.getText(), new String(password.getPassword()), addr, port)){
					
					case GameModel.LOGIN_ALREADY_LOGGED:
						JOptionPane.showMessageDialog(null,"Já se encontra logado!");
						System.out.println("Já se encontra logado!");
						break;
					case GameModel.LOGIN_FULL:
						JOptionPane.showMessageDialog(null,"Servidor Cheio!");
						System.out.println("Servidor Cheio!");
						break;
					case GameModel.LOGIN_INVALID:
						JOptionPane.showMessageDialog(null,"Dados de login invalidos!");
						System.out.println("Dados de login invalidos!");
						break;
					case GameModel.LOGIN_OK:
						//JOptionPane.showMessageDialog(null,"Ligado com sucesso!");
						System.out.println("Ligado com sucesso!");
						break;
					case GameModel.CONNECTION_ERROR:
						JOptionPane.showMessageDialog(null,"Erro na ligação!");
						System.out.println("Erro na ligação!");
						break;
						
					default: System.out.println("Resultado: " + res);
					JOptionPane.showMessageDialog(null,"Resultado: " + res);
					}
					
				} catch (UnknownHostException e1) {
					e1.printStackTrace();
				}catch(Exception ex){
					ex.printStackTrace();					
				}
				
				
			
			}
		});
		
	}
}
